package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Voucher;
import com.hmdp.mapper.VoucherMapper;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher> implements IVoucherService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryVoucherOfShop(Long shopId) {
        //传入商铺id
        List<Voucher> vouchers = getBaseMapper().queryVoucherOfShop(shopId);
//        System.out.println("查询到的优惠券信息: " + vouchers);
//        查询到的优惠券信息: [Voucher(id=1, shopId=1, title=50元代金券, subTitle=周一至周日均可使用,
//                rules=全场通用\n无需预约\n可无限叠加\不兑现、不找零\n仅限堂食, payValue=4750, actualValue=5000,
//                type=0, status=null, stock=null, beginTime=null, endTime=null, createTime=null,
//                updateTime=null), Voucher(id=10, shopId=1, title=100元代金券, subTitle=周一至周五均可使用,
//                rules=全场通用\n无需预约\n可无限叠加\不兑现、不找零\n仅限堂食, payValue=8000, actualValue=10000,
//                type=1, status=null, stock=99, beginTime=2024-04-10T10:09:17, endTime=2025-10-16T12:09:04,
//                createTime=null, updateTime=null), Voucher(id=11, shopId=1, title=100元代金券,
//                subTitle=周一直周五均可用, rules=全场通用\n无需预约\n无可叠加\不兑现,不找零\n仅限堂食, payValue=8000,
//                actualValue=10000, type=1, status=null, stock=100, beginTime=2024-04-14T10:09:17,
//                endTime=2026-04-04T12:12:12, createTime=null, updateTime=null)]

        // 查询优惠券信息
        return Result.ok(vouchers);
        // 返回结果
    }

    @Override
    @Transactional
    public void addSeckillVoucher(Voucher voucher) {
        // 保存优惠券
        save(voucher);
        // 保存秒杀信息
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());
        seckillVoucherService.save(seckillVoucher);
        stringRedisTemplate.opsForValue().set("seckill:stock"+voucher.getId(),voucher.getStock().toString());
    }
}
